<template>
  <div class="tag-edit-page">
    <div class="tag-container">
      <div class="tag-group">
        <div class="tag-title">已有标签</div>
        <div class="tags">
          <van-tag
              v-for="(tag, index) in tags"
              :key="index"
              type="primary"
              size="medium"
              round
              plain
              @click="removeTag(index)"
          >
            {{ tag }}
            <van-icon name="cross" slot="close" />
          </van-tag>
        </div>
      </div>

      <div class="tag-group">
        <div class="tag-title">添加新标签</div>
        <div class="add-tag">
          <van-field
              v-model="newTag"
              placeholder="输入标签名称"
              @keydown.enter="addTag"
          />
          <van-button type="primary" round @click="addTag">
            <van-icon name="plus" /> 添加标签
          </van-button>
        </div>
      </div>
    </div>

    <div class="submit-area">
      <van-button round block type="primary" @click="onSubmit">
        保存修改
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {showFailToast, showSuccessToast} from 'vant';
import {getCurrentUser} from "../../sevices/User.ts";
import type {UserType} from "../../models/User";
import {updateUserInfo} from "../../api/User.ts";
// import { updateUserTags } from '../../api/User.ts'; // 假设这是更新标签的API

const router = useRouter();
const route = useRoute();

// 存储标签列表
const tags = ref<string[]>([]);
// 存储新标签输入值
const newTag = ref('');
// 存储当前用户ID
const userId = ref<number | null>(null);
// 当前登录用户
const user = ref<UserType>();

// 初始化标签数据
onMounted(async () => {
  try {
    // 从路由参数获取标签数据
    const tagsParam = route.query.tags;
    if (tagsParam) {
      // 解析JSON字符串为数组
      tags.value = Array.isArray(tagsParam) ? tagsParam : [];
    }

    // 获取用户ID（根据你的项目逻辑获取）
    // 这里假设你有一个获取当前用户的方法
    user.value = await getCurrentUser();
    userId.value = Number(user.value?.id);
  } catch (error) {
    console.error('解析标签数据出错:', error);
    showFailToast('标签数据加载失败');
    router.back();
  }
});

// 添加新标签
const addTag = () => {
  const tag = newTag.value.trim();
  if (!tag) {
    showFailToast('标签不能为空');
    return;
  }
  // 检查标签是否已存在
  if (tags.value.includes(tag)) {
    showFailToast('标签已存在');
    return;
  }
  // 添加新标签
  tags.value.push(tag);
  // 清空输入框
  newTag.value = '';
};

// 删除标签
const removeTag = (index: number) => {
  tags.value.splice(index, 1);
};

// 表单提交处理
const onSubmit = async () => {
  if (!userId.value) {
    showFailToast('用户信息缺失');
    return;
  }

  try {
    // 将标签数组转换为JSON字符串
    const tagsJson = JSON.stringify(tags.value);
    // 调用API更新标签
    const result = await updateUserInfo(userId.value, 'tags', tagsJson);

    // 根据API返回结果处理
    // @ts-ignore
    if (result.code === 0 && result.data) {
      showSuccessToast('修改标签成功');
      router.back(); // 返回上一页
    } else {
      // @ts-ignore
      showFailToast('修改标签失败' + (result.description ? `${result.description}` : ''));
    }
  } catch (error) {
    console.error('更新标签出错:', error);
    showFailToast('网络错误，请稍后再试');
  }
};
</script>

<style scoped>
.tag-edit-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.tag-container {
  padding: 16px;
}

.tag-group {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.tag-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #333;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.add-tag {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.submit-area {
  padding: 16px;
}
</style>